package org.example.controller;

import com.github.pagehelper.PageInfo;
import com.wf.captcha.SpecCaptcha;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.User;
import org.example.mapper.UserDao;
import org.example.service.UserService;
import org.example.utils.AuthControl;
import org.example.utils.RedisPond;
import org.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制层。
 *
 * @author mybatis-flex-helper automatic generation
 * @since 1.0
 */
@Slf4j
@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    private UserDao userDao;

    Jedis jedis = RedisPond.getJedis();

    private static final String CAPTCHA_KEY = "captcha";

    /**
     * 验证码
     * 请求地址：http://localhost:8090/usercaptcha
     * @param response
     * @throws Exception
     */
    @Operation(summary = "验证码",tags = {"用户"},description = "验证码")
    @RequestMapping(value ="/captcha", method = RequestMethod.GET)
    public void captcha(HttpServletResponse response) throws Exception {
        // 英文与数字验证码
        SpecCaptcha captcha = new SpecCaptcha();

        captcha.setLen(4);// 验证字符数

        // 结果
        String result = captcha.text();

        jedis.setex(CAPTCHA_KEY,60*30,result.toLowerCase());
        // 响应到前端
        captcha.out(response.getOutputStream());
    }


    /**
     * 请求地址：http://localhost:8090/userlogin?username=阿斌&password=123&captcha=
     * @throws Exception
     */
    @PostMapping("/login")
    public Map<String,Object> login(@RequestBody Map<String, Object> loginParam) throws Exception {
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> data = new HashMap<>();

        //listByMap的参数
        data.put("account",loginParam.get("account"));

        //验证码为空
        if(loginParam.get("captcha") == null||loginParam.get("captcha").toString().equals("")) {
            return Result.fileMap("验证码不能为空");
        }
        //验证码错误
        if(!loginParam.get("captcha").toString().equalsIgnoreCase(jedis.get(CAPTCHA_KEY))) {
            return Result.fileMap("验证码不正确");
        }
        //用户名密码为空
        if(loginParam.get("account") == "" || loginParam.get("password") == "") {
            return Result.fileMap("用户名或者密码不能为空");
        }

        //查询数据库
        List<User> users = userService.listByMap(data);

        //用户不存在
        if(users.size()==0) {
            return Result.fileMap("用户名不存在");
        }

        User user = users.get(0);

        Map<String,Object> parameter = new HashMap<>();

        if(!user.getPassword().equals(loginParam.get("password"))) {
            String loginFailCountStr = "";
            if(RedisPond.getJedis().get("loginFailCount") == null||RedisPond.getJedis().get("loginFailCount").equals("")){
                RedisPond.getJedis().set("loginFailCount","0");
                RedisPond.getJedis().setex("loginFailCount",60*5,"0");
            }
            RedisPond.getJedis().incr("loginFailCount");
            loginFailCountStr = RedisPond.getJedis().get("loginFailCount");
            int loginFailCount = Integer.valueOf(loginFailCountStr);
            System.out.println("loginFailCount>>>>>>>>>>>:"+loginFailCount);
            if(loginFailCount>=3){
                parameter.put("status","1");
                parameter.put("updated_time",new Date());
                parameter.put("id",user.getUserId());
                RedisPond.getJedis().del("loginFailCount");
                userService.updateByMap(parameter);
                return Result.fileMap("你已输入密码错误多次，账号以冻结");
            }
            return Result.fileMap("密码错误！");
        }

        //根据用户id创建token
        String token = AuthControl.createToken(users.get(0).getUserId());
        jedis.setex("token",60*30,token);

        //返回的数据
        map.put("user",users.get(0));
        map.put("token",token);
        map.put("finishDateTime",AuthControl.getFinishDateTime(token));
        return Result.successMap(map);
    }


    /**
     * 添加
     *
     * @param user
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("/save")
    public Map<String,Object>  save(@RequestBody User user) {
        if(user.getAccount() == null || user.getAccount().equals("")){
            return Result.fileMap("用户名不能为空");
        }
        if(user.getPassword() == null || user.getPassword().equals("")){
            return Result.fileMap("密码不能为空");
        }
        if(user.getUsername() == null || user.getUsername().equals("")){
            return Result.fileMap("昵称不能为空");
        }

        return Result.successMap("注册成功");
    }


    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {

        if (user.getAccount() == null || "".equals(user.getAccount())) {
            return Result.fileMap("账号能为空");
        }
        if (user.getUsername() == null || "".equals(user.getUsername())) {
            return Result.fileMap("用户名不能为空");
        }
        if (user.getPassword() == null || "".equals(user.getPassword())) {
            return Result.fileMap("密码不能为空");
        }
            List<User> users = userService.getByAccount(user.getAccount());
            user.setUserRole(1);
        if (users.size() > 0) {
            return Result.fileMap("账号已存在");
        }

        boolean user1 = userService.save(user);
        if (!user1) {
            return Result.fileMap("注册失败");
        }
        return Result.successMap("注册成功");
    }


    /**
     * 根据主键删除
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @DeleteMapping("/remove/{id}")
    public Map<String,Object> remove(@PathVariable Serializable id) {
        User user = userService.getById(id);
        if (user == null){
            return Result.fileMap("用户不存在");
        }
        if(user.getDeleted().equals(1)){
            return Result.fileMap("用户已被删除");
        }
        return Result.successMap("删除成功");
    }


    /**
     * 根据主键更新
     *
     * @param user
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PutMapping("/update")
    public Map<String,Object> update(@RequestBody User user) {
        if(user.getUserId() == null){
            return Result.fileMap("id不能为空");
        }

        if(StringUtils.isEmpty(user.getAccount())){
            return Result.fileMap("用户名不能为空");
        }
        if(StringUtils.isEmpty(user.getPassword())){
            return Result.fileMap("密码不能为空");
        }
        if(StringUtils.isEmpty(user.getUsername())){
            return Result.fileMap("昵称不能为空");
        }
        boolean b = userService.updateById(user);
        if(!b){
            return Result.successMap("更新失败");
        }
        return Result.successMap("更新成功");
    }


    /**
     * 查询所有
     *
     * @return 所有数据
     */
    @GetMapping("/list")
    public Map<String,Object> list() {
        Map<String,Object> map = new HashMap<>();
        map.put("userList",new PageInfo<>(userService.list()));
        return Result.successMap(map);
    }


    /**
     * 根据主键获取详细信息。
     * 请求地址：http://localhost:8090/usergetInfo/1
     * @param id user主键
     * @return 详情
     */
    @GetMapping("/getInfo/{id}")
    public Map<String,Object> getInfo(@PathVariable Serializable id) {
        return Result.successMap(userService.getById(id));
    }

}